﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;

namespace WeavingCommon
{
    [Export, PartCreationPolicy(CreationPolicy.Shared)]
    public class TargetPathFinder
    {
        IConfig config;
        IBuildEngine buildEngine;
        Logger logger;

        [ImportingConstructor]
        public TargetPathFinder(IConfig config, IBuildEngine buildEngine, Logger logger)
        {
            this.config = config;
            this.buildEngine = buildEngine;
            this.logger = logger;
        }

        public void Execute(string environmentKey)
        {

            if (string.IsNullOrWhiteSpace(config.TargetPath))
            {
                try
                {
                    config.TargetPath = buildEngine.GetEnvironmentVariable(environmentKey, true).First();
                    logger.LogMessage("\tYou did not define the WeavingTask.TargetPath. So it was extracted from the BuildEngine.");
                }
                catch (Exception exception)
                {
                    throw new WeavingException(string.Format(
                        @"Failed to extract target assembly path from the BuildEngine. 
Please raise a bug here http://code.google.com/p/notifypropertyweaver/issues/list with the below exception text.
The temporary work-around is to change the weaving task as follows 
<WeavingTask ... TargetPath=""@({1})"" />
Exception details: {0}", exception, environmentKey));
                }
            }
            if (!File.Exists(config.TargetPath))
            {
                throw new WeavingException(string.Format("TargetPath \"{0}\" does not exists. If you have not done a build you can ignore this error.", config.TargetPath));
            }

        }
    }
}